package client.common.util;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.UUID;

@Slf4j
public class EncryptUtil {

    private static final byte[] KEY = {-23, -98, -27, -56, -56, 88, 81, 109, 87, 55, -57, -83, 74, 16, -53, -20, -128, -48, -53, -36, 117, -122, -9, 56};

    /**
     * 哈希加密并加盐 不可逆加密
     * 摘要加密 MD5
     */

    public static String encryptHash(String content) {
        return DigestUtil.md5Hex(content);
    }


    /**
     * 对称加密并加盐 AES
     * 把盐拼接在密文后面
     */

    public static String encryptSym(String content) {
        // 每次都获得一个随机的盐 长度是固定的32位
        String salt = UUID.randomUUID().toString().replace("-", "");

        AES aes = SecureUtil.aes(KEY);

        String encrypt = content + salt;

        byte[] encrypt1 = aes.encrypt(encrypt);

        //固定的48位
        byte[] saltE = aes.encrypt(salt);

        return Arrays.toString(mergeBytes(saltE, encrypt1));
    }

    /**
     * 解密
     */

    public static String decrypt(String content) {
        AES aes = SecureUtil.aes(KEY);

        byte[] bytes = StringToBytes(content);

        //前48位是盐 先获取到盐
        byte[] saltE = new byte[48];

        System.arraycopy(bytes, 0, saltE, 0, 48);

        //转换位字符串
        String saltDe = aes.decryptStr(saltE);

        byte[] c = new byte[bytes.length - 48];

        System.arraycopy(bytes, 48, c, 0, c.length);

        String decrypt = aes.decryptStr(c);

        return decrypt.split(saltDe)[0];
    }

    /**
     * 这个字符串需要是是一个byte数组被arrays.toString转换的
     */
    private static byte[] StringToBytes(String s) {
        s = s.replace("[", "").replace("]", "").replace(" ", "");
        String[] split = s.split(",");
        byte[] b = new byte[split.length];
        for (int i = 0; i < split.length; i++) {
            b[i] = Byte.parseByte(split[i]);
        }
        return b;
    }

    /**
     * 合并俩个byte数组
     */

    private static byte[] mergeBytes(byte[] a, byte[] b) {
        byte[] c = new byte[a.length + b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        return c;
    }



}
